'use strict'
const uuid = require('uuid/v1')
const fs = require('fs')
const path = require('path')
const toArray = require('stream-to-array')
/*
* @ctx          context对象            必传
* @size         限制文件大小            默认2  单位M
*/
const fileUploadFile = async (ctx, size = 2, folderName) => {
    const stream = await ctx.getFileStream()
    // 判断文件类型，存入对应的目录
    const imgtype = ['image/gif', 'image/jpeg', 'image/jpg', 'image/png', 'image/svg']
    let url = 'public/static/other/'
    if (imgtype.includes(stream.mimeType)) {
        url = 'public/static/image/'
    }
    const catalog = path.join(ctx.app.baseDir, 'app', url)

    // 截取文件类型
    let filename = stream.filename
    let t = filename.split('.')
    let len = t.length
    let filetypeName = '.' + t[len - 1]

    // 获取文件大小
    const filesize = parseInt((stream.readableLength / 1024) / 1024)
    if (filesize > size) {
        ctx.throw(403, '文件大大了，最多' + size + 'M', {
            code: 'file_max'
        })
    }

    try {
        const parts = await toArray(stream)
        const buf = Buffer.concat(parts)
        const nameid = uuid()
        const target = catalog + nameid + filetypeName
        fs.writeFileSync(target, buf)
        return url + nameid + filetypeName
    } catch (e) {
        return {
            message: '文件上传失败'
        }
    }
}

const Controller = require('../base.js')

class FileController extends Controller {
    // 上传文件
    async index() {
        const {ctx} = this
        try {
            let url = await fileUploadFile(ctx)
            ctx.success({
                url,
                origin: 'local'
            })
        } catch (e) {
            ctx.throw(403, '上传失败', {
                code: 'upload_error',
                errors: e.message
            })
        }

    }
}

module.exports = FileController
